/*
** func.c for  in /home/lund/Projets/mallocv2
** 
** Made by florian dewulf
** Login   <dewulf_f@epitech.net>
** 
** Started on  Tue Feb  5 10:25:14 2013 florian dewulf
** Last update Thu Feb  7 12:15:40 2013 florian dewulf
*/

#include	<unistd.h>
#include	"malloc.h"

t_malloc	*g_list = (void *)0;

void		*xsbrk(unsigned int size)
{
  t_malloc	*new;
  t_malloc	*list;

  list = g_list;
  new = sbrk(BLOCK + size);
  if (new == ERROR)
    return (ERROR);
  new->size = size;
  new->next = NULL;
  new->state = TRUE;
  if (list == NULL)
    {
      g_list = new;
      new->prev = NULL;
    }
  else
    {
      while (list->next)
	list = list->next;
      list->next = new;
      new->prev = list;
    }
  return (new);
}

t_malloc	*search_maille(void *ptr)
{
  t_malloc	*list;

  list = g_list;
  if (g_list == NULL || (g_list != NULL && (t_malloc *)ptr < list) ||
      ptr > sbrk(0))
    return (NULL);
  while (list && list < (t_malloc *)ptr && (((void *)(list + 1) + list->size) < ptr))
    list = list->next;
  if (list == NULL)
    return (NULL);
  return (list);
}

unsigned int	get_size(unsigned int size)
{
  size -= 1;
  size >>= 2;
  size <<= 2;
  size += 4;
  return (size);
}

void		*separate(unsigned int size)
{
  t_malloc	*new;

  new = g_list;
  while (new)
    {
      if (new->state == FALSE && new->size >= size + BLOCK + 4)
	{
	  return (tool_where(new, size));
	}
      new = new->next;
    }
  return (NULL);
}

void		*get_maille(t_malloc *p, unsigned int size)
{
  /*if (p->prev && (p->prev->size + p->size + BLOCK) == size)
    {
      printf("1\n");
      return (prev_equal(p));
    }
  else if (p->prev && (p->size + p->prev->size + 4) >= size)
    {
      printf("2\n");
      return (prev_split(p->prev, p, size));
    }
  else if (p->next && (p->size + p->next->size + BLOCK) == size)
    {
      printf("3\n");
      return (next_equal(p));
    }
  else if (p->next && (p->size + p->next->size + BLOCK + 4) >= size)
    {
      printf("4\n");
      return (next_split(p, p->next, size));
    }
  else
    {
      printf("5\n");
      return (where_maille(p, size));
    }*/
  return (alloc(p, size));
}
